package cn.hinglo.permission.service;

import cn.hinglo.common.util.SysCommonKit;
import cn.hinglo.permission.entity.ApiQueryFilter;
import cn.hinglo.permission.model.Api;
import cn.hutool.core.bean.BeanUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;

/**
 * @author HingLo
 * @createTime: 2020-09-09 10:43:48
 * @description: ApiService 服务层
 */
@Slf4j
public class ApiService {

    /**
     * Api列表
     *
     * @param request 请求信息
     * @return Api分页后集合
     */
    public Map<String, Object> listApiService(ApiQueryFilter request) {
        Map<String, Object> param = BeanUtil.beanToMap(request);
        Page<Record> list = Db.template("api.list", param).paginate(request.getPage(), request.getPageSize());
        return SysCommonKit.pageKit(list.getTotalRow(), list.getList());
    }

    /**
     * 添加Api
     *
     * @param api Api对象信息
     * @return 操作结果
     */
    public Integer addApiService(Api api) {
        api.setUpdateTime(new Date());
        // 默认新建
        if (api.getId() == null) {
            api.setState(0);
            api.save();
        } else {
            api.setState(2);
            api.update();
        }
        return api.getId();
    }

    /**
     * 删除Api对象
     *
     * @param id Api对象的唯一ID
     * @return 操作结果
     */
    public boolean deleteApiService(Integer id) {
        return id != null && Api.dao.deleteById(id);
    }

    /***
     * 更新接口状态
     * @param id id
     * @param state  状态值
     * @return 返回结果
     */
    public boolean updateApiService(Integer id, Integer state) {
        Api api = Api.dao.findById(id);
        if (api == null) {
            return false;
        }
        api.setState(state);
        return api.update();
    }
}

